<template>
	<div>
		<div class="container">
			<div class="toolbar mt-2">
				<a-form ref="searchRef" :model="searchState" @finish="current = 1; loading = true; initData()">
					<a-row :gutter="20">
						<a-col :span="6">
							<a-form-item label="城市公司/专业公司">
								<a-select v-model:value="searchState.company_id" :show-search="true" placeholder="请选择城市公司/专业公司" :options="companyOptions" option-filter-prop="label" allow-clear></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item label="选择项目">
								<a-select v-model:value="searchState.project_id" :show-search="true" placeholder="请选择" :options="innerProjectOptions" option-filter-prop="label"></a-select>
							</a-form-item>
						</a-col>
						<a-col :span="3">
							<a-form-item>
								<a-space>
									<a-button type="primary" html-type="submit">
										<search-outlined />搜索
									</a-button>
								</a-space>
							</a-form-item>
						</a-col>
					</a-row>
				</a-form>
			</div>

			<div class="mt-2">
				<!--
				v-if="!loading"使得:default-expand-all-rows="true"生效
				-->
				<a-table v-if="!loading" :columns="columns" :scroll="tableScroll" children-column-name="children" :default-expand-all-rows="false" :data-source="psSource" :pagination="pagination" :loading="loading" @change="initData">
					<template #bodyCell="{ column, record }">
						<template v-if="column.dataIndex === 'operation'">
							<a-space>
								<a-button v-permission="140" type="link" @click="show(record)">
									<right-outlined />查看
								</a-button>
							</a-space>
						</template>
						<template v-else-if="column.key === 'flowStatus'">
							<div>
								<flow-model :module-id="'planjx'" :item-id="record.id" @change="changeFlowStatusData2"></flow-model>
							</div>
						</template>
					</template>
				</a-table>
			</div>
		</div>
	</div>
</template>

<script setup>
import { reactive, ref, computed, getCurrentInstance, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
const projectlist = ref([]);
const companyOptions = ref([]);
const mtypelist = ref([]);
const { proxy } = getCurrentInstance();
import dayjs from "dayjs";

import { SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined, RightOutlined } from "@ant-design/icons-vue";

import { post } from "../utils";

import { usePagination } from "vue-request";

const router = useRouter();
const route = useRoute();
const query = route.query;
const searchRef = ref();
const searchState = reactive({});
post("department/projects", { type: 3, get_type: 1 }).then(({ data }) => {
	projectlist.value = data.map(d => {
		return {
			value: d.id,
			label: d.name,
			parseIds: d.parent_ids.split(',').map(item => parseInt(item)),
		};
	});
});
post("department/projects?type=2", {
	parent_ids: JSON.stringify([78, 24]),
}).then(({ data }) => {
	companyOptions.value = data.map(d => {
		return {
			value: d.id,
			label: d.name
		};
	});
});
const innerProjectOptions = computed(() => {
	let options = [];
	if (!projectlist.value.length) return options;
	if (searchState.company_id) {
		options = projectlist.value.filter((item) => {
			return item.parseIds.includes(searchState.company_id);
		})
	} else {
		options = projectlist.value;
	}
	if (!options.filter(item => item.value === searchState.project_id).length) {
		searchState.project_id = null;
	}
	return options;
})
mtypelist.value = [
	{ label: "主要材料", value: 2 },
	{ label: "周转材料", value: 57 },
	{ label: "机械类", value: 61 }
];
const columns = [
	{
		title: "项目名称",
		dataIndex: "name",
		sorter: false,
		width: 150,
		ellipsis: true,
		fixed: "left"
	},
	{
		title: "库存数量",
		dataIndex: "total_qty",
		sorter: false,
		width: 150,
		align: "center",
		customRender: ({ text, record, index, column }) => {
			return parseInt(text) === parseFloat(text) ? parseInt(text) : text;
		}
	},
	{
		title: "操作",
		dataIndex: "operation",
		sorter: false,
		fixed: "right",
		width: 300,
		align: "center"
	}
];
const tableScroll = computed(() => ({
	x: document.documentElement.clientWidth - 650
}));

const { data, loading, run, current, pageSize, total } = usePagination(params => {
	const search = {};
	if (searchState.company_id) {
		search.project_ids = projectlist.value.filter((item) => {
			return item.parseIds.includes(searchState.company_id);
		}).map(item => item.value).join(',');
		if (!search.project_ids) {
			return [];
		}
	}
	return post("projectstock/project", { ...params, ...searchState, ...search });
}, {
	defaultParams: [
		{
			page_size: 10
		}
	],
	pagination: {
		currentKey: "page",
		pageSizeKey: "page_size",
		totalKey: "total"
	}
});

const show = record => {
	//console.log(record);
	//router.push(`projectstock/info/` + record.project_id);
	router.push(`projectstock/info/${record.project_id}`);
};

const psSource = computed(() =>
	(data.value?.data || []).map(d => {
		if (d.children?.length === 0) delete d.children;
		return d;
	})
);

const pagination = computed(() => ({
	total: total.value,
	current: current.value,
	pageSize: pageSize.value
}));

const initData = (pag, filters, sorter) => {
	pag = Object.assign(
		{
			current: current.value,
			pageSize: pageSize.value
		},
		pag || {}
	);
	filters = { ...filters, ...searchState };
	const query = {};
	if (pag?.pageSize) {
		query['page_size'] = pag?.pageSize;
	}
	if (pag?.current) {
		query['page'] = pag?.current;
	}
	router.replace({ query: {
		...query,
		...filters
	}})
	run({
		page_size: pag?.pageSize,
		page: pag?.current,
		sort_field: sorter?.field,
		sort_order: sorter?.order,
		...filters
	});
};
if (query) {
	if (query.company_id) searchState.company_id = parseInt(query.company_id);
	if (query.project_id) searchState.project_id = parseInt(query.project_id);
	const pag = {};
	if (query.page) {
		pag['current'] = parseInt(query.page);
	}
	if (query.pageSize) {
		pag['pageSize'] = parseInt(query.page_size);
	}
	initData(pag);
}

</script>
<style scoped lang="scss">
.container {
	background: #fff;
	padding: 12px;
}
</style>
